package vn.appsmobi.adapter;

import java.util.ArrayList;

import vn.appsmobi.R;
import vn.appsmobi.ulti.Log;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public abstract class BaseDataAdapter<T> extends BaseAdapter
{
  private static final String TAG = "BaseDataAdapter";
  protected Context mContext;
  protected ArrayList<T> mData;
  protected boolean mDataValid;

  public BaseDataAdapter(Context context)
  {
    this.mContext = context;
    this.mDataValid = false;
  }

  protected void bindBackground(View view, int position)
  {
    if (getCount() == 1)
      view.setBackgroundResource(R.drawable.list_item_single_bg);
    else
    {      
      if (position == 0)
        view.setBackgroundResource(R.drawable.list_item_top_bg);
      else if (position == -1 + getCount())
        view.setBackgroundResource(R.drawable.list_item_bottom_bg);
      else
        view.setBackgroundResource(R.drawable.list_item_middle_bg);
    }
	  view.setBackgroundResource(R.drawable.list_item_middle_bg);
  }

  public abstract void bindView(View paramView, int paramInt, T object);

  public int getCount()
  {
    if ((this.mDataValid) && (this.mData != null))
    	return this.mData.size();
    else	
    	return 0;
  }

  public ArrayList<T> getData()
  {
    ArrayList<T> localArrayList = new ArrayList<T>();
    if (this.mData != null)
      localArrayList.addAll(this.mData);
    return localArrayList;
  }

  public T getItem(int position)
  {
    if ((this.mDataValid) && (this.mData != null))
    	return  this.mData.get(position);     
      return null;
  }

  public long getItemId(int position)
  {
    if ((this.mDataValid) && (this.mData != null));
    	return position;
  }

  public View getView(int position, View convertView, ViewGroup parent)
  {
     
    if (!this.mDataValid)
      throw new IllegalStateException("this should only be called when the data is valid");
    if ((position < 0) || (position >= this.mData.size()))
      throw new IllegalStateException("couldn't get view at this position " + position);
    
    T localObject = this.mData.get(position);    
    View localView = convertView;
    
    if (convertView == null)
    {
    	localView = newView(this.mContext, localObject, parent);

    }
    bindView(localView, position, localObject);
    bindBackground(localView, position);
    
    return localView;
  }

  public abstract View newView(Context paramContext, T object, ViewGroup paramViewGroup);

  public void updateData(ArrayList<T> data)
  {
	  if(data != null && !data.isEmpty())
	  {
		  Log.v(""+data.size());
		  this.mDataValid = true;
	      this.mData = data;
	      notifyDataSetChanged();
	  }
	  else
	  {
		  Log.v("notifyDataSetInvalidated");
		  this.mDataValid = false;
	      notifyDataSetInvalidated();
	  }
	  
  }
}
